package com.gujia.concurrent.condition;

import com.gujia.concurrent.reentrant.Warehouse;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class WareHouseCondition extends Warehouse{

    private boolean isFull = false;
    private ReentrantLock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();


    public void put() {

        lock.lock();
        if(!this.isFull){
            try{
                System.out.println("放满了，来取");
                isFull=!isFull;
                //唤醒非空线程
                notEmpty.signal();
            }catch (Exception e){

            }finally {
                lock.unlock();
            }

        }else {

            try {
                notFull.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public void get(){

        lock.lock();
        if(this.isFull){

            try{
                System.out.println("空了，来放");

                isFull = !isFull;
                notFull.signal();
            }catch (Exception e){

            }finally {
                lock.unlock();
            }

        }else{

            try {
                notEmpty.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
